﻿using System;
using System.Linq;
using System.Web.Mvc;
using easyccms.BusinessLayer;
using easyccms.BusinessLayer.Entities;
using easyccms.BusinessLayer.Repositories;
using easyccms.WebUI.Areas.Administrator.Models;
using easyccms.WebUI.Code;
using easyccms.WebUI.Infrastructure;

namespace easyccms.WebUI.Areas.Administrator.Controllers
{
    /// <summary>
    /// Article controller.
    /// </summary>
    public class ArticleController : Controller, IAdminController
    {

        /// <summary>
        /// Gets the article repository.
        /// </summary>
        private IArticleRepository ArticleRepository
        {
            get { return DependencyInjector.Resolve<IArticleRepository>(); }
        }

        /// <summary>
        /// Gets the menu item repository.
        /// </summary>
        private IMenuItemRepository menuItemRepository
        {
            get { return DependencyInjector.Resolve<IMenuItemRepository>(); }
        }

        /// <summary>
        /// Gets the menu repository.
        /// </summary>
        private IMenuRepository MenuRepository
        {
            get { return DependencyInjector.Resolve<IMenuRepository>(); }
        }

        /// <summary>
        /// Gets the unit of work.
        /// </summary>
        private IUnitOfWork UnitOfWork
        {
            get { return ArticleRepository.GetUnitOfWork(); }
        }

        /// <summary>
        /// Gets the user provider.
        /// </summary>
        private UserProvider UserProvider
        {
            get
            {
                return new UserProvider();
            }
        }

        //
        // GET: /Administrator/Article/

        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {

            return View(this.ArticleRepository.All.Where(x=>!x.Deleted));
        }

        //
        // GET: /Administrator/Article/Create

        /// <summary>
        /// Creates this instance.
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            ArticleCreateModel articleCreateModel = new ArticleCreateModel
                                                        {
                                                            MenusItems =
                                                                this.menuItemRepository.All.Where(x => !x.Deleted).
                                                                AsEnumerable().Select(
                                                                    x =>
                                                                    new SelectListItem()
                                                                        {
                                                                            Text =
                                                                                string.Format("{0}-{1}", x.Menu.Name,
                                                                                              x.Name),
                                                                            Value = x.MenuItemId.ToString()
                                                                        }).ToList()
                                                        };



            return View(articleCreateModel);
        }

        //
        // POST: /Administrator/Article/Create

        /// <summary>
        /// Creates the specified collection.
        /// </summary>
        /// <param name="articleCreate">The article create.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(ArticleCreateModel articleCreate)
        {
            if (ModelState.IsValid)
            {
                Article article = new Article();
                article.Text = articleCreate.Text;
                article.Title = articleCreate.Title;
                article.Enabled = true;
                
                article.DisplayUntil = DateTime.Now;
                article.User = UserProvider.GetCurrentUser();
                article.Created = DateTime.Now;
                article.Deleted = false;
                //article.MenuItem = this.menuItemRepository.Load(articleCreate.MenuItemId);

                try
                {
                    this.UnitOfWork.StartTransaction();
                    this.ArticleRepository.Save(article);
                    this.UnitOfWork.CommitTransaction();

                    return RedirectToAction("Index");
                }
                catch
                {
                    this.UnitOfWork.RollbackTransaction();
                }
            }

            ArticleCreateModel articleCreateModel = new ArticleCreateModel
            {
                Text = articleCreate.Text,
                Title = articleCreate.Title,
                MenusItems =
                    this.menuItemRepository.All.Where(x => !x.Deleted).
                    AsEnumerable().Select(
                        x =>
                        new SelectListItem()
                        {
                            Text =
                                string.Format("{0}-{1}", x.Menu.Name,
                                              x.Name),
                            Value = x.MenuItemId.ToString(),
                            Selected = articleCreate.MenuItemId==x.MenuItemId
                        }).ToList()
            };
            return View(articleCreateModel);
        }
        
        //
        // GET: /Administrator/Article/Edit/5
 
        public ActionResult Edit(int id)
        {
            ArticleCreateModel articleCreate = new ArticleCreateModel();
            Article article = this.ArticleRepository.Load(id);
            articleCreate.ArticleId = id;
            articleCreate.Title = article.Title;
            articleCreate.Text = article.Text;
            //articleCreate.MenuItemId = article.MenuItem.MenuItemId;
            articleCreate.MenusItems = this.menuItemRepository.All.Where(x => !x.Deleted).
                AsEnumerable().Select(
                    x =>
                    new SelectListItem()
                        {
                            Text =
                                string.Format("{0}-{1}", x.Menu.Name,
                                              x.Name),
                            Value = x.MenuItemId.ToString(),
                            Selected = articleCreate.MenuItemId == x.MenuItemId
                        }).ToList();



            return View(articleCreate);
        }

        //
        // POST: /Administrator/Article/Edit/5

        [HttpPost]
        public ActionResult Edit(ArticleCreateModel articleCreate)
        {
            if (ModelState.IsValid)
            {
                Article article = this.ArticleRepository.Load(articleCreate.ArticleId);
                article.Text = articleCreate.Text;
                article.Title = articleCreate.Title;
                article.Enabled = true;

                article.DisplayUntil = DateTime.Now;
                article.User = UserProvider.GetCurrentUser();
                article.Created = DateTime.Now;
                article.Deleted = false;
                //article.MenuItem = this.menuItemRepository.Load(articleCreate.MenuItemId);

                try
                {
                    this.UnitOfWork.StartTransaction();
                    this.ArticleRepository.Save(article);
                    this.UnitOfWork.CommitTransaction();

                    return RedirectToAction("Index");
                }
                catch
                {
                    this.UnitOfWork.RollbackTransaction();
                }
            }

            ArticleCreateModel articleCreateModel = new ArticleCreateModel
            {
                Text = articleCreate.Text,
                Title = articleCreate.Title,
                MenusItems =
                    this.menuItemRepository.All.Where(x => !x.Deleted).
                    AsEnumerable().Select(
                        x =>
                        new SelectListItem()
                        {
                            Text =
                                string.Format("{0}-{1}", x.Menu.Name,
                                              x.Name),
                            Value = x.MenuItemId.ToString(),
                            Selected = articleCreate.MenuItemId == x.MenuItemId
                        }).ToList()
            };
            return View(articleCreateModel);
        }
        
        public ActionResult MoveToBin(int id)
        {
            Article articleToUpdate = this.ArticleRepository.Load(id);
            articleToUpdate.Deleted = true;
            this.UnitOfWork.StartTransaction();
            this.ArticleRepository.Save(articleToUpdate);
            this.UnitOfWork.CommitTransaction();

            return RedirectToAction("Index");
        }

        public ActionResult Bin()
        {
            return View(this.ArticleRepository.All.Where(x => x.Deleted));
        }

        public ActionResult BinDelete(int id)
        {
            TempData["SelectedTab"] = "Article";
            Article articleToUpdate = this.ArticleRepository.Load(id);
            articleToUpdate.Deleted = true;
            this.UnitOfWork.StartTransaction();
            this.ArticleRepository.Delete(articleToUpdate);
            this.UnitOfWork.CommitTransaction();

            return RedirectToAction("Bin", "Management");
        }

        public ActionResult BinRestore(int id)
        {
            TempData["SelectedTab"] = "Article";
            Article articleToUpdate = this.ArticleRepository.Load(id);
            articleToUpdate.Deleted = false;
            this.UnitOfWork.StartTransaction();
            this.ArticleRepository.Save(articleToUpdate);
            this.UnitOfWork.CommitTransaction();

            return RedirectToAction("Bin", "Management");
        }
    }
}
